package com.lyw.GeoLocationClient.ui.fragment;


import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.TextView;
import com.lyw.GeoLocationClient.R;
import com.lyw.GeoLocationClient.utils.NetUtil;
import com.lyw.GeoLocationClient.utils.T;
import com.lyw.GeoLocationClient.service.LBSClient;
import com.lyw.GeoLocationClient.ui.GeotableItem;
import com.lyw.GeoLocationClient.ui.adapter.GroupListAdapter;
import com.lyw.GeoLocationClient.ui.quickaction.ActionItem;
import com.lyw.GeoLocationClient.ui.quickaction.QuickAction;
import com.lyw.GeoLocationClient.ui.view.AddRosterItemDialog;
import com.lyw.GeoLocationClient.ui.view.GroupNameView;
import com.xlistview.IphoneTreeView;

import java.util.ArrayList;
import java.util.HashMap;

import static com.lyw.GeoLocationClient.utils.LogUtils.LOGD;

public class LeftFragment extends Fragment implements View.OnClickListener {

    private IphoneTreeView xListView;
    private LayoutInflater mInflater;
    private ImageView mTitleAddView;

    private int mLongPressGroupId, mLongPressChildId;
    private LBSClient mClient;
    private GroupListAdapter mAdapter;
    private HashMap<String, ArrayList<GeotableItem>> mGroupMap;
    private ArrayList<String> mGroupList;
    private Handler mHandler;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.main_left_fragment, container,
                false);
        return view;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView(view);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mClient = LBSClient.getInstance();
        mGroupMap = mClient.getGroupMap();
        mHandler = new Handler();
//        mApplication = PushApplication.getInstance();
//        mUserDB = mApplication.getUserDB();
//        mMsgDB = mApplication.getMessageDB();
//        mRecentDB = mApplication.getRecentDB();
//        mSpUtil = mApplication.getSpUtil();
//        mSoundListener = new SoundPullEventListener(getActivity());
//        mSoundListener.addSoundEvent(State.PULL_TO_REFRESH, R.raw.pull_event);
//        mSoundListener.addSoundEvent(State.RESET, R.raw.reset_sound);
//        mSoundListener.addSoundEvent(State.REFRESHING, R.raw.refreshing_sound);

    }

    @Override
    public void onResume() {
        super.onResume();
        LOG("onResume");
        initData();
        mAdapter = new GroupListAdapter(getActivity(),xListView, mGroupList, mGroupMap);
        xListView.setAdapter(mAdapter);
//        updateUserData();
    }

    private void initData() {
        mGroupMap = mClient.getGroupMap();

        if (mGroupList == null) {
            mGroupList = new ArrayList<String>();
        } else {
            mGroupList.clear();
        }
        mGroupList.addAll(mGroupMap.keySet());

    }

    public void updateUserData() {
        initData();
        LOG("updateUserData + " + mGroupMap);
        mAdapter.requery(mGroupList, mGroupMap);
    }

    private void initView(View view) {
        mInflater = LayoutInflater.from(getActivity());
        // prepareQuickActionBar();
        // title
//        view.findViewById(R.id.title_left_btn).setVisibility(View.GONE);
        view.findViewById(R.id.title_right_btn).setVisibility(View.GONE);
        TextView title = (TextView) view.findViewById(R.id.ivTitleName);
        title.setText(R.string.left_title_name);
        mTitleAddView = (ImageView) view
                .findViewById(R.id.ivTitleBtnRightImage);
        mTitleAddView.setImageResource(R.drawable.setting_add_account_white);
        mTitleAddView.setOnClickListener(this);


        xListView = (IphoneTreeView) view.findViewById(R.id.friend_xlistview);

        xListView.setGroupIndicator(null);
        xListView.setHeaderView(mInflater.inflate(
                R.layout.contact_buddy_list_group, xListView, false));
//        xListView.setEmptyView(getActivity().findViewById(R.id.empty));

//        xListView.setPullLoadEnable(false);// 禁止下拉加载更多
//        xListView.setXListViewListener(new XExpandableListView.IXListViewListener() {
//
//            @Override
//            public void onRefresh() {
//                // TODO Auto-generated method stub
//                // handler.postDelayed(add, 2000);
//                initUserData();
//                xListView.setAdapter(mAdapter);
//                xListView.stopRefresh();
//                xListView.setRefreshTime(System.currentTimeMillis());
//            }
//
//            @Override
//            public void onLoadMore() {
//
//            }
//
//        });

        xListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {

            @Override
            public boolean onChildClick(ExpandableListView parent, View v,
                                        int groupPosition, int childPosition, long id) {
//                User u = (User) mAdapter.getChild(groupPosition, childPosition);
//                mMsgDB.clearNewCount(u.getUserId());// 新消息置空
//                Intent toChatIntent = new Intent(getActivity(),
//                        ChatActivity.class);
//                toChatIntent.putExtra("user", u);
//                startActivity(toChatIntent);
                return false;
            }
        });
        xListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {

            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view,
                                           int position, long id) {
                int groupPos = (Integer) view.getTag(R.id.xxx01); // 参数值是在setTag时使用的对应资源id号
                int childPos = (Integer) view.getTag(R.id.xxx02);
                mLongPressGroupId = groupPos;
                mLongPressChildId = childPos;
                if (childPos == -1) {// 长按的是父项
                    // 根据groupPos判断你长按的是哪个父项，做相应处理（弹框等）
                    showGroupQuickActionBar(view);
                } else {
                    // 根据groupPos及childPos判断你长按的是哪个父项下的哪个子项，然后做相应处理。
                    // T.showShort(getActivity(), "onClick child position = "
                    // + groupPos + ":" + childPos);
                    showChildQuickActionBar(view);

                }

                return false;
            }
        });
//        xListView.setOnScrollListener(new AbsListView.OnScrollListener() {
//
//            @Override
//            public void onScrollStateChanged(AbsListView view, int scrollState) {
//                // TODO Auto-generated method stub
//            }
//
//            @Override
//            public void onScroll(AbsListView view, int firstVisibleItem,
//                                 int visibleItemCount, int totalItemCount) {
//                // TODO Auto-generated method stub
////                LOG("onScroll " + firstVisibleItem);
//
////                xListView.setSelectionFromTop(0,0);
//            }
//        });


    }


    private void showGroupQuickActionBar(View view) {
        QuickAction quickAction = new QuickAction(getActivity(), QuickAction.HORIZONTAL);
        quickAction
                .addActionItem(new ActionItem(0, getString(R.string.show_on_map)));
        quickAction.addActionItem(new ActionItem(1,
                getString(R.string.add_friend)));
        quickAction
                .setOnActionItemClickListener(new QuickAction.OnActionItemClickListener() {

                    @Override
                    public void onItemClick(QuickAction source, int pos,
                                            int actionId) {
                        // 如果没有连接直接返回
//                        if (!isConnected()) {
//                            T.showShort(TraceMainActivity.this,
//                                    R.string.conversation_net_error_label);
//                            return;
//                        }
                        switch (actionId) {
                            case 0:
//                                String groupName = mRosterAdapter.getGroup(
//                                        mLongPressGroupId).getGroupName();
//                                if (TextUtils.isEmpty(groupName)) {// 系统默认分组不允许重命名
//                                    T.showShort(this,
//                                            R.string.roster_group_rename_failed);
//                                    return;
//                                }
//                                renameRosterGroupDialog(mRosterAdapter.getGroup(
//                                        mLongPressGroupId).getGroupName());
                                break;
                            case 1:

//                                new AddRosterItemDialog(TraceMainActivity.this,
//                                        mXxService).show();// 添加联系人
                                break;
                            default:
                                break;
                        }
                    }
                });
        quickAction.show(view);
        quickAction.setAnimStyle(QuickAction.ANIM_GROW_FROM_CENTER);
    }

    private void showChildQuickActionBar(View view) {
        QuickAction quickAction = new QuickAction(getActivity(), QuickAction.HORIZONTAL);
//        quickAction.addActionItem(new ActionItem(0, getString(R.string.add)));
//        quickAction
//                .addActionItem(new ActionItem(1, getString(R.string.rename)));
        quickAction.addActionItem(new ActionItem(2, getString(R.string.move)));
        quickAction
                .addActionItem(new ActionItem(3, getString(R.string.delete)));
        quickAction
                .setOnActionItemClickListener(new QuickAction.OnActionItemClickListener() {

                    @Override
                    public void onItemClick(QuickAction source, int pos,
                        int actionId) {
                        GeotableItem item = (GeotableItem) mAdapter.getChild(mLongPressGroupId, mLongPressChildId);
                        if (item != null) {

                            LOG("select item : " + item.toString());

                        } else {
                            return;
                        }
                        if (!NetUtil.isNetConnected(getActivity())) {
                            T.showShort(getActivity(),
                                    R.string.net_error_tip);
                            return;
                        }

                        switch (actionId) {
                            case 0:
                                break;
                            case 1:
                                break;
                            case 2:
                                moveGeoItemToGroupDialog(item.getGeoId());
                                break;
                            case 3:
                                break;

                            default:
                                break;
                        }
                    }
                });
        quickAction.show(view);
    }


    void moveGeoItemToGroupDialog(final int geoid) {
        LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View group = inflater
                .inflate(R.layout.moverosterentrytogroupview, null);
        final GroupNameView gv = (GroupNameView) group
                .findViewById(R.id.moverosterentrytogroupview_gv);
        gv.setGroupList(mGroupList);
        new AlertDialog.Builder(getActivity())
                .setTitle(R.string.change_group)
                .setView(group)
                .setPositiveButton(android.R.string.ok,
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,
                                                int which) {
                                LOG("new group: " + gv.getGroupName());
                                if ((NetUtil.isNetConnected(getActivity()))) {
//                                    mClient.modifyProp(geoid, GeotableDBHelper.GROUP, gv.getGroupName());
                                }
                            }
                        }).setNegativeButton(android.R.string.cancel, null)
                .create().show();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ivTitleBtnRightImage:
//                XXService xxService = mFragmentCallBack.getService();
//                if (xxService == null || !xxService.isAuthenticated()) {
//                    return;
//                }
                AddRosterItemDialog addRosterItemDialog = new AddRosterItemDialog(getActivity(), -1);// 添加联系人
                addRosterItemDialog.show();
                break;

            default:
                break;
        }
    }


    public void LOG(String msg) {
        LOGD(LeftFragment.class, msg);
    }

}
